package com.yunji.news.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yunji.news.common.Result;
import com.yunji.news.entity.Article;
import com.yunji.news.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 文章控制器
 *
 * @author yunji
 * @since 2024-11-23
 */
@RestController
@RequestMapping("/articles")
@CrossOrigin
public class ArticleController {
    
    @Autowired
    private ArticleService articleService;
    
    /**
     * 分页查询文章列表
     */
    @GetMapping
    public Result<IPage<Article>> getArticles(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) Long schoolId,
            @RequestParam(required = false) Integer isTop,
            @RequestParam(required = false) Integer isHot,
            @RequestParam(required = false) String keyword) {
        
        IPage<Article> result = articleService.getArticlePage(page, size, categoryId, schoolId, isTop, isHot, keyword);
        return Result.success(result);
    }
    
    /**
     * 获取文章详情
     */
    @GetMapping("/{id}")
    public Result<Article> getArticle(@PathVariable Long id) {
        Article article = articleService.getById(id);
        if (article == null) {
            return Result.error("文章不存在");
        }
        
        // 增加浏览次数
        articleService.increaseViewCount(id);
        
        return Result.success(article);
    }
    
    /**
     * 获取首页推荐内容
     */
    @GetMapping("/home/recommended")
    public Result<Map<String, List<Article>>> getHomeRecommended() {
        Map<String, List<Article>> result = articleService.getHomeRecommended();
        return Result.success(result);
    }
    
    /**
     * 获取热门文章
     */
    @GetMapping("/hot")
    public Result<List<Article>> getHotArticles(@RequestParam(defaultValue = "10") Integer limit) {
        List<Article> articles = articleService.getHotArticles(limit);
        return Result.success(articles);
    }
    
    /**
     * 记录文章浏览
     */
    @PostMapping("/{id}/view")
    public Result<String> viewArticle(@PathVariable Long id) {
        articleService.increaseViewCount(id);
        return Result.success();
    }
}